import { createRouter, createWebHistory } from 'vue-router'

import {ElMessage} from 'element-plus'

import useCustomerStore from '@/stores/customer'

const routes = [
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/Register.vue'),
    // 路由独享守卫
    beforeEnter: (to,from) => {
      const customerStore = useCustomerStore()
      if( customerStore.logined ) {
        ElMessage({message: `警告: 您目前已登录，请先退出后再尝试注册！`, type: 'warning'})
        return '/main';
      }
    },
    meta: {
      title: '用户注册'
    }
  },
  {
    path: '/login',
    name: 'login',
    alias:'/',
    component: () => import('@/views/Login.vue'),
    // 路由独享守卫
    beforeEnter: (to,from) => {
      const customerStore = useCustomerStore()
      if( customerStore.logined ) {
        ElMessage({message: `警告: 您目前已登录！`, type: 'warning'})
        return '/main';
      }
    },
    meta: {
      title: '用户登录'
    }
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/Main.vue'),
    // 路由独享守卫
    beforeEnter: (to,from) => {
      // 获得 customerStore 实例
      const customerStore = useCustomerStore()
      if( !customerStore.logined ) {
        ElMessage({message: `警告: 您尚未登录，请先登录！`, type: 'warning'})
        return '/login';
      }
    },
    // 定义子路由(即嵌套路由)
    children: [
      {
        path: 'files',
        name: 'allFiles',
        alias: '',
        component: () => import('@/views/AllFiles.vue'),
        meta: {
          title: '所有文件'
        }
      },
      {
        path: 'own',
        name: 'myFiles',
        component: () => import('@/views/MyFiles.vue'),
        meta: {
          title: '我的文件'
        }
      },
      {
        path: 'upload',
        name: 'uploadFile',
        component: () => import('@/views/UploadFile.vue'),
        meta: {
          title: '文件上传'
        }
      }
    ]
  },
  {
    path: '/logout',
    name: 'logout',
    component: () => import('@/views/Main.vue'),
    // 路由独享守卫
    beforeEnter: (to,from) => {
      // 获得 customerStore 实例
      const customerStore = useCustomerStore()
      // 完成注销操作
      customerStore.signOut()
      return '/login'
    }
  }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})
  
  export default router